// JavaScript Document

var spotlights = {

    init: function() {
        
        this.bindHeaderLinks();
        this.bindImageLinks();
    },
    
    bindHeaderLinks: function() {
        $("#add-link").click(function(e) {
            e.preventDefault();
            
            var url = $(this).attr("href");
            
            $.get(url, function(data) {
                $p.showDialog({
                    title: "Add New Spotlight",
                    content: data,
                    okButtonText: 'Create Spotlight',
                    okButtonAction: function() {
                        $("#spotlight-add-form").submit();
                        return false;
                    }
                    
                }, function() {
                    
                    // if we are editting (i.e. description field is present) the initialise
                    // the TinyMCE control and register the form handlers
                    if( $p.$("#description") ) {
                        // make the description field an html editor
                        ui.htmlMiniEditor("description");
            
                        $p.all("form", function(el) {
                            el.onsubmit = function() {
                                tinyMCE.triggerSave();

                                return $p(this).validate({
                                    menu_header: "Title",
                                    menu_subheader: "Subtitle",
                                    description: "Description",
                                    uploadFile: "Spotlight File To Upload"
                                });
                            }
                        });
                    }
                    
                    $("#uploadFile").change(function() {
                        spotlights._setFileExtInfo( this );
                    });
                });
            });
        });
        
        $("#del-selected-link").click(function(e) {
            e.preventDefault();
            
            if( !confirm('Delete Selected Spotlight Image(s) From The Site?') ) {
                return;
            }
            
            var checked = [];
            $(".image-list input[type=checkbox]").each(function() {
                if( this.checked ) {
                    checked.push( this.value );
                
                    var $this = $(this);
                    $this.parents("li").fadeOut('slow', function() {
                        $this.parents("li").remove();
                    });
                }
            });
            
            var query = "ids=" + checked;
            $.post( $(this).attr('href'), query);
        });
        
        // add check all event listener
        $p('#checkall').bind('click', function() {
            var items = $p.all(".image-list input[type=checkbox]");
            
            for(var  i = 0; i < items.length; i++) {
                items[i].checked = this.checked;
                
                if( this.checked ) {
                    $(items[i]).parents("li").addClass("selected");
                }
                
                else {
                    $(items[i]).parents("li").removeClass("selected");
                }
                
            }
        });
    },
	
    bindImageLinks: function() {
        
        $(".edit-link").click(function(e) {
            e.preventDefault();
            
            var url = $(this).attr("href");
            $.get(url, function(data) {
                $p.showDialog({
                    title: 'Edit Spotlight',
                    content: data,
                    okButtonText: "Save Changes",
                    okButtonAction: function() {
                        var query = $("#spotlight-edit-form").serialize();
                        
                        $.post(url, query);
                    }
                }, function() {
                    // make the description field an html editor
                    ui.htmlMiniEditor("description");
                });
            });
        });
        
        $(".delete-link").click(function(e) {
            e.preventDefault();
            
            if( !confirm('Delete Selected Spotlight Image From The Site?') ) {
                return;
            }
		
            var $link = $(this);
            $.get( $link.attr('href'), function() {
                $link.parents("li").fadeOut('fast', function() {
                    $link.parents("li").remove();
                });
            });
        });
        
        
        $p(".image-list input[type=checkbox]").bind('change', function() {
            if( this.checked ) {
                $(this).parents("li").addClass("selected");
            }
            
            else {
                $(this).parents("li").removeClass("selected");
                $("#checkall").removeAttr("checked");
            }
        });
        
        // add event listener for preview links
        $p(".image-list img").bind('click', function(){
            
            var img = "<img src='" + $p(this).attr("src") + "' />";
            
            $p.showMessage({
                title: $p(this).attr("data-title"),
                content: img
            });
        });
		
        // add the event listener for all the publishing links available
        $(".cms-publish-link, .cms-unpublish-link").click( function(e) {
            e.preventDefault();
            
            if( $(this).hasClass('cms-publish-link') ) {
                spotlights.setApproved('unpublish', this );
            } else {
                spotlights.setApproved('publish', this );
            }
        });
    },
    
    _setFileExtInfo: function(field) {
        
        var extField = document.getElementById("ext");
        var fileName = field.value;
        var ext = fileName.substring( fileName.lastIndexOf(".") + 1, fileName.length );
        var extFound = false;
        var extList = document.getElementById("allowedExt").value;
        var exts = extList.split(",");
	
        for(var i = 0; i < exts.length; i++) {
            if(exts[i].toLowerCase() == ext.toLowerCase()) {
                extFound = true;
                break;
            }
        }
												
        if( !extFound ) {
            alert("Chosen File Is Not In The Right Format. \n\nFile Format Must Be In Any Of These Formats: " + extList.toUpperCase()
                + "\n\nPlease Cross-Check Your File Selection");
													
            field.value = "";
        } else {
            extField.value = "." + ext;
        }
												
    },
	
    /**
     * Approves or disapproves a spotlights image from being displayed
     * 
     * @param action
     * @param linkEl
     */
    setApproved: function(action, linkEl) {
        var url = $(linkEl).attr("href");
        var query = "action=" + action + "&id="	+ linkEl.id;
		
        $p.post( url, query, function() {
																		   
            if( action == "publish" ) {
                linkEl.className = 'cms-publish-link';	
                linkEl.title = 'Published (Click To Unpublish)';
            } else {
                linkEl.className = 'cms-unpublish-link';
                linkEl.title = 'Unpublished (Click To Publish Now)';
            }
        });	
    }
};

$(document).ready(function() {
    spotlights.init();
});